package com.example.demo.blockqueue;


import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @desc: 延迟任务<br />
 * @author: Jingbo Hu<br/>
 * @time：2021年01⽉21⽇<br/>
 * @version：v1.0.0<br>
 */
public class DelayTask implements Delayed {
    String taskName;
    long time;

    public DelayTask(String taskName, long givenTime, long delayTime, TimeUnit unit) {
        this.taskName = taskName;
        this.time = givenTime + unit.toMillis(delayTime);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    public String getTaskName() {
        return this.taskName;
    }

    public static long getDelayTime(long givenTime, long delayTime, TimeUnit unit) {
        return givenTime + unit.toMillis(delayTime);
    }
}
